package com.example.netty.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Socket套接字 服务端
 *
 * @author LSQ
 * @since 2023/2/16 21:09
 */
public class Server {

    public static void main(String[] arg) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.execute(() -> {
            socketServerStart(100);
        });
        executorService.execute(() -> {
            socketServerStart(101);
        });
        executorService.execute(() -> {
            socketServerStart(102);
        });

        // 保持主线程空转
        while (true) {

        }
    }

    private static void socketServerStart(Integer port) {
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            Socket socket = serverSocket.accept();
            //获取输入流
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //获取输出流
            pw = new PrintWriter(socket.getOutputStream(), true);
            while (true) {
                //获取接收的信息
                String str = br.readLine();

                //发送相同的数据给客户端
                pw.println(str);

                if ("bye".equals(str)) {
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                pw.close();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }

}
